package com.wish.finance.controller;


import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wish.common.core.usconfig.common.MsgResult;
import com.wish.common.security.utils.SecurityUtils;
import com.wish.finance.alipay.AlibabapayGateWayUtils;
import com.wish.finance.entity.*;
import com.wish.finance.entity.vo.TCwPaymentPlanVo;
import com.wish.finance.service.ITCfContractService;
import com.wish.finance.service.ITCwPaymentPlanService;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 高锦涛
 * @since 2022-03-26
 */
@RestController
@Log
public class TCwPaymentPlanController {

    @Autowired
    ITCwPaymentPlanService itCwPaymentPlanService;


    //添加方法
    @PostMapping("save")
    public void save(@RequestBody TCwPaymentPlanVo tCwPaymentPlanVo) {
        ArrayList<CostType> costTypes = tCwPaymentPlanVo.getCostTypes();
        Long id = null;
        for (CostType costType : costTypes) {
            tCwPaymentPlanVo.setId(id);
            //生成随机单号
            String s = RandomUtil.randomStringUpper(10);
            tCwPaymentPlanVo.setPayOrderNo(s);
            tCwPaymentPlanVo.setItemType(costType.getItemType());
            tCwPaymentPlanVo.setPaymentAmount(costType.getPaymentAmount());
            tCwPaymentPlanVo.setRealPaymentAmount(costType.getRealPaymentAmount());
            tCwPaymentPlanVo.setCreateUserid(SecurityUtils.getUserId());
            tCwPaymentPlanVo.setCreateTime(new Date());
            itCwPaymentPlanService.save(tCwPaymentPlanVo);
        }
    }


    /*查询付款计划*/
    @PostMapping("paymentList")
    public PageInfo<TCwPaymentPlanVo> paymentList(@RequestBody TCwPaymentPlanVo tCwPaymentPlanVo) {
        PageHelper.startPage(tCwPaymentPlanVo.getPageNum(), tCwPaymentPlanVo.getPageSize());
        List<TCwPaymentPlanVo> list = itCwPaymentPlanService.paymentList(tCwPaymentPlanVo);
        PageInfo<TCwPaymentPlanVo> tCwPaymentPlanVoPageInfo = new PageInfo<>(list);
        return tCwPaymentPlanVoPageInfo;
    }


    /*获取所有账单类型*/
    @GetMapping("itemTypeList")
    public ItemType[] itemTypeList() {
        ItemType[] values = ItemType.values();
        return values;
    }

    /*获取所有付款状态*/
    @GetMapping("payStateList")
    public PayState[] payStateList() {
        PayState[] values = PayState.values();
        return values;
    }

    /*获取所有付款类型*/
    @GetMapping("billTypeList")
    public BillType[] payTypeList() {
        BillType[] values = BillType.values();
        return values;
    }

    /*获取所有支付方式*/
    @GetMapping("payMethodList")
    public PayMethod[] payMethodList() {
        PayMethod[] values = PayMethod.values();
        return values;
    }

    /*支付宝支付*/
    @PostMapping("settles")
    public String settles(@RequestBody TCwPaymentPlan tCwPaymentPlanVo) throws AlipayApiException {
        String orderID = tCwPaymentPlanVo.getId() + "";
        String total_amount = tCwPaymentPlanVo.getPaymentAmount() + "";
        String order = AlibabapayGateWayUtils.createOrder(orderID, total_amount, "主题", JSON.toJSONString(tCwPaymentPlanVo));
        //String order = MyAlipayUtil.createOrderForm(tCwPaymentPlanVo.getId() + "", tCwPaymentPlanVo.getPayNumber() + "", "主题");
        return order;
    }

    @PostMapping("/notify")
    public void alyPayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("支付宝支付成功回调");
        //这里拿到支付宝通知数据
        // 将异步通知中收到的待验证所有参数都存放到map中
        Map<String, Object> params = convertRequestParamsToMap(request);
        System.out.println(params.toString());

        //获取到对象了
        String s = params.get("body").toString();
        TCwPaymentPlan tCwPaymentPlan = JSON.parseObject(s, TCwPaymentPlan.class);

//        获取付款状态
        String tradeStatus = params.get("trade_status").toString();

//        交易支付成功。
        if ("TRADE_SUCCESS".equals(tradeStatus)) {
            tCwPaymentPlan.setPaidTime(new Date());
            tCwPaymentPlan.setPayState(PayState.YFK);
            itCwPaymentPlanService.saveOrUpdate(tCwPaymentPlan);
        }
//           未付款交易超时关闭，或支付完成后全额退款          交易创建，等待买家付款。
        if ("TRADE_CLOSED".equals(tradeStatus) || "WAIT_BUYER_PAY".equals(tradeStatus)) {
            tCwPaymentPlan.setPayState(PayState.YZZ);
            itCwPaymentPlanService.saveOrUpdate(tCwPaymentPlan);
        }

/*        String paramsJson = JSON.toJSONString(params);
        log.info("支付宝回调，{}" + paramsJson);
        Map<String, String> map = JSON.parseObject(paramsJson, new TypeReference<Map<String, String>>() {
        });
        System.out.println(map);
        return aliPayService.aliPayNotify(map, response);*/


    }

    /**
     * 将request中的参数转换成Map
     */
    private static Map<String, Object> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        Map<String, String[]> map = new HashMap<String, String[]>();
        map = request.getParameterMap();
        Iterator entries = map.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = null;
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object objvalue = entry.getValue();
            if (objvalue == null) {
                value = null;
            } else if (objvalue instanceof String[]) {
                /**条件如果成立，objvalue就是一个数组，需要将它转换成为字符串，并拼接上逗号，并吧末尾的逗号去掉*/
                String[] values = (String[]) objvalue;
                for (int i = 0; i < values.length; i++) {
                    value = values[i] + ",";//这里我拼接的是英文的逗号。
                }
                value = value.substring(0, value.length() - 1);//截掉最后一个逗号。
            } else {
                value = objvalue.toString();
            }
            log.info("key:" + name);
            log.info("value:" + value);
            returnMap.put(name, value);
        }
        Iterator it = returnMap.keySet().iterator();
        while (it.hasNext()) {
            Object key = it.next();
            if (returnMap.get(key) == null || "".equals(((String) returnMap.get(key)).trim())) {
                returnMap.put((String) key, null);
            }
        }
        return returnMap;
    }

    @Autowired
    ITCfContractService itCfContractService;

    @GetMapping("/getMsg")
    public MsgResult getMsg(TCfContract contract) {
        TCfContract byId = itCfContractService.getById(contract.getId());
        return MsgResult.succeed(byId);
    }

}
